package com.mybk.room;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private AppDatabase mDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_add).setOnClickListener(this);
        findViewById(R.id.btn_search).setOnClickListener(this);
        initData();
    }

    private void initData() {
        mDatabase = Room.databaseBuilder(getApplicationContext(),
                AppDatabase.class, "database-name").build();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_add:
                add();
                break;
            case R.id.btn_search:
                search();
                break;
        }
    }

    private void add() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String time = System.currentTimeMillis() + "";
                mDatabase.userDao().insert(new User("lin", time));
            }
        }).start();
    }

    private void search() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<User> data = mDatabase.userDao().getAll();
                for (User user : data) {
                    Log.i("xy", "---> user " + user.firstName + " " + user.lastName);
                }
            }
        }).start();
    }

}